// 配置路由的地方

import Vue from "vue";
import VueRouter from "vue-router";

// 模块化路由
import routes from "./routes";
Vue.use(VueRouter);
// 引入store
import store from "@/store";
// 先把VueRouter原型对象的push，先保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
// 重写push|replace
// 第一个参数 ：告诉原来的方法向哪跳 传哪些参数
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    // call ||apply区别
    // 相同：都可以调用函数一次，都可以覆盖函数的上下文一次
    // 不同点：call与apply传递参数，：call传递参数用逗号隔开，apply方法执行，传递数组

    originPush.call(this, location, resolve, reject);
  } else {
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject);
  } else {
    originReplace.call(this, location, resolve, reject);
  }
};

let router = new VueRouter({
  // 配置路由
  routes,
  scrollBehavior(to, from, savedPosition) {
    return { y: 0 }; /* y = 0 代表滚动条距离顶部 100 像素 */
  },
});

router.beforeEach((to, from, next) => {
  const token = store.state.users.token;
  if (token && !store.state.users.userInfo.username) {
    // 有token没有用户信息请求用户信息
    store.dispatch("initUserInfo");
    // 下次切换不用重复请求了
  }

  next();
});
export default router;
